﻿using System;
using LibMSNP.HTTP;
using System.Text;
using System.Text.RegularExpressions;

namespace LibMSNP.MSNPProtocol
{
    public class MSNPCommand : IMSNPCommand
    {
        protected HTTPHeader _messageHeader;
        protected string _command;
        protected int _transactionId;
        protected string _payload;
        protected string[] _parameters;

        public MSNPCommand(string command, int trID, HTTPHeader header, string payload = null, params string[] parameters)
        {
            _command = command;
            _transactionId = trID;
            _payload = payload;
            _parameters = new string[parameters.Length];
            parameters.CopyTo(_parameters, 0);
            _messageHeader = header;
        }

        public MSNPCommand(string command, int trID, string payload = "", params string[] parameters)
        {
            _messageHeader = null;
            _command = command;
            _transactionId = trID;
            _payload = payload;
            _parameters = new string[parameters.Length];
            parameters.CopyTo(_parameters, 0);
        }

        public static IMSNPCommand CommandFromByte(byte[] buf)
        {
            Encoding enc = UTF8Encoding.UTF8;
            string msg = new string(enc.GetChars(buf));
            string[] cmd;
            msg = msg.Remove(msg.IndexOf('\0'));
            cmd = msg.Split(new string[] { "\\r\\n" }, StringSplitOptions.None);
            Regex cmdreg = new Regex("^([A-Z]+) ([0-9]*) (.*)\\r\\n$");
            string[] tmp = cmdreg.Split(cmd[0]);

            for (int i = 0; i < tmp.Length; i++)
            {

            }
            return null;
        }

        #region IMSNPCommand Members

        public string Command
        {
            get { return _command; }
        }

        public string[] Parameters
        {
            get { return _parameters; }
        }

        public int TransactionId
        {
            get { return _transactionId; }
        }

        public string Payload
        {
            get { return _payload; }
        }

        #endregion

        public override string ToString()
        {
            string val = _command + " " + _transactionId + " " ;
            for (int i = 0; i < _parameters.Length; i++)
            {
                val += _parameters[i] + " ";
            }
            val += "\r\n";
            if (_payload.Length > 0)
                val += _payload;
            return val;
        }
    }
}
